import React, { useState } from "react";
import { Button, Form, Input, message } from "antd";
import { Link } from "react-router-dom";
import { getEmailCode, forget } from "@/api/api";

const Forget: React.FC = () => {
  const { Search } = Input;
  const [loadingState, setLoadingState] = useState(false);
  const [formLoading, setFormLoading] = useState(false);
  const search = (value: any) => {
    setLoadingState(true);
    getEmailCode(value).then((res) => {
      setLoadingState(false);
      if (res.code === 200) {
        message.success(res.msg);
      } else {
        message.warn(res.msg);
      }
    });
  };

  const finish = (value: any) => {
    setFormLoading(true);
    const { user_password, user_name, code } = value;
    forget({ user_password, user_name, code }).then((res) => {
      setFormLoading(false);
      if (res.code === 200) {
        message.success(res.msg);
      } else {
        message.warning(res.msg);
      }
    });
  };
  return (
    <>
      <div className={""}>
        <Form className={"form"} name="login" onFinish={finish}>
          <Form.Item
            name="user_name"
            rules={[
              {
                type: "email",
                message: "请输入正确的邮箱",
              },
              {
                required: true,
                message: "请输入邮箱",
              },
            ]}
          >
            <Search
              placeholder={"你的邮箱"}
              loading={loadingState}
              enterButton={"发送验证码"}
              onSearch={search}
            />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[{ required: true, message: "验证码是必须填写的" }]}
          >
            <Input placeholder={"收到的验证码"} />
          </Form.Item>
          <Form.Item
            name="user_password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password placeholder={"设置一个新密码"} />
          </Form.Item>
          <Form.Item
            name="user_re_password"
            rules={[
              {
                required: true,
                message: "请重复输入密码",
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("user_password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次密码不一致"));
                },
              }),
            ]}
          >
            <Input.Password placeholder={"重复新密码"} />
          </Form.Item>
          <div className={"login-nav"}>
            <Link to={"/login"}>记得密码，请去登录</Link>
          </div>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={formLoading}>
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </>
  );
};
export default Forget;
